<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="auto" size="small">

      <el-form-item label="" prop="informtCategoryE">
        <el-input
          v-model="queryParams.informtTitleE"
          clearable
          :placeholder="$t('input')"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">{{$t("search")}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t("reset")}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:informt:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >{{$t("add")}}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:informt:edit']"
          :disabled="single"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="handleUpdate"
        >{{$t("edit")}}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:informt:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >{{$t("delete")}}
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="informtList" @selection-change="handleSelectionChange">
      <!--    <el-table v-loading="loading"  :data="informtList" :header-cell-style="{bordercolor: '#f10c0c', background:'#0477fd',color:'#fdfdfd',}" @selection-change="handleSelectionChange" >-->
      <el-table-column align="center" type="selection" width="55"/>
      ,


      <el-table-column align="center" :label="$t('informt6')" prop="informtTitle"/>
      <el-table-column align="center" :label="$t('informt5')" prop="informtText" :show-overflow-tooltip="true" />
      <el-table-column align="center" class-name="small-padding" :label="$t('createTime')" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" class-name="small-padding fixed-width" :label="$t('controls')">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:informt:query']"
            icon="el-icon-view"
            size="mini"
            type="text"
            @click="handleView(scope.row)"
          >{{$t('view1')}}
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改角色管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body center width="700px">
      <el-form ref="form" :disabled=isinput :model="form" :rules="rules" label-width="120px">


        <el-form-item :label="$t('category')" prop="parentId">
          <treeselect v-model="form.parentId" :disabled=isinput :normalizer="normalizer" :options="informtypeOptions"
                      :placeholder="$t('input')"/>
        </el-form-item>


        <el-form-item :label="$t('newsHeadline')" prop="informtTitle">
          <el-input v-model="form.informtTitle" :placeholder="$t('input')"/>
        </el-form-item>

        <el-form-item :label="$t('newsContent')" prop="informtText">
          <el-input v-model="form.informtText" :placeholder="$t('input')" type="textarea"/>
        </el-form-item>


        <el-form-item :label="$t('s3')" prop="informtRoleid">
          <el-select v-model="form.productIds" multiple :placeholder="$t('input')">
            <el-option
              v-for="item in receptionRole"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"

            ></el-option>
          </el-select>

        </el-form-item>


        <el-form-item :label="this.$t('menu17')" prop="informtAttachment">
          <image-upload v-model="form.informtAttachment"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show=isinpututool type="primary" @click="submitForm">{{$t("ok")}}</el-button>
        <el-button @click="cancel">{{$t("cancel")}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addInformt, delInformt, getInformt, listInformt, listInformtRoles, updateInformt} from "@/api/system/informt";


import {listInformtype} from "@/api/system/informtype";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Informt",
  components: {
    Treeselect
  },
  data() {
    return {
      deptOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色管理表格数据
      informtList: [],
      informtypeOptions: [],
      // 弹出层标题
      title: "",
      receptionRole: [],
      isinput: false,
      isinpututool: true,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        informtCategory: null,
        informtTitle: null,
        informtText: null,
        informtRoleid: null,
        informtAttachment: null,
        informtCategoryE: null,
        informtTitleE: null,
        informtTextE: null,
        informtRoleidE: null,
        informtAttachmentE: null,
        productId: null,
        parentId: null

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

        informtTitle: [
          {required: true, message: this.$t('s1'), trigger: "blur"}
        ],
        informtText: [
          {required: true, message: this.$t('s2'), trigger: "blur"}
        ]


      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
      }
      // 分隔符是竖杠|不是斜杠/,注意此正则表达式 /{(y|m|d|h|i|s|a)+}/g
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
          return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str;
    },
    getTreeselect() {
      listInformtype().then(response => {
        this.informtypeOptions = [];

        const data = {productId: response.data[0].parentId, productName: response.data[0].productName, children: []};
        data.children = this.handleTree(response.data, "productId", "parentId");
        this.informtypeOptions.push(data);
      });
    },
    /** 查询角色管理列表 */
    getList() {
      this.loading = true;
      listInformt(this.queryParams).then(response => {
        this.informtList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        informtId: null,
        informtCategory: null,
        informtTitle: null,
        informtText: null,
        informtRoleid: null,
        informtAttachment: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        informtCategoryE: null,
        informtTitleE: null,
        informtTextE: null,
        informtRoleidE: null,
        informtAttachmentE: null,
        productId: null,
        productIds: [],
        productName: null,
        parentId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.informtId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      listInformtRoles(null).then(response => {
        this.receptionRole = response.rows;
        this.form.parentId = 0;
        this.open = true;
        this.isinpututool = true;
        this.isinput = false;
        this.title = this.$t('add');
      });


    },
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();

      this.isinpututool = true;
      this.isinput = false;

      const informtId = row.informtId || this.ids


      getInformt(informtId).then(response => {
        this.form = response.data;

        this.receptionRole = response.receptionRole;
        this.form.parentId = response.data.informtCategory
        this.$set(this.form, "productIds", response.roles);

        this.open = true;
        this.title = this.$t('edit');
      });
    },
    /** 修改按钮操作 */
    handleView(row) {
      this.reset();
      this.getTreeselect();

      this.isinpututool = false;
      this.isinput = true;

      const informtId = row.informtId || this.ids


      getInformt(informtId).then(response => {
        this.form = response.data;

        this.receptionRole = response.receptionRole;
        this.form.parentId = response.data.informtCategory
        this.$set(this.form, "productIds", response.roles);

        this.open = true;
        this.title = this.$t('view1');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.informtId != null) {
            this.form.informtCategory = this.form.parentId
            updateInformt(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('modifiedSuccessfully'));
              this.open = false;
              this.getList();
            });
          } else {
            this.form.informtCategory = this.form.parentId
            addInformt(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('newSuccessfullyAdded'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const informtIds = row.informtId || this.ids;
      this.$modal.confirm(this.$t('menu16') + informtIds ).then(function () {
        return delInformt(informtIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('de1'));
      }).catch(() => {
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.productId,
        label: node.productName,
        children: node.children
      };
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/informt/export', {
        ...this.queryParams
      }, `informt_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
